package com.shimao.celnet.payment.util;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by ensure.xu on 2017/12/7.
 */
public class MyDateUtil {
    public static final String formatDefaultTimestamp = "yyyy-MM-dd HH:mm:ss";
    public static final String format_yyyy_MM_dd_HHmmssSSS = "yyyy-MM-dd HH:mm:ss.SSS";
    public static final String format_yyyy_MM_dd_HHmm = "yyyy-MM-dd HH:mm";
    public static final String format_yyyy_MM_dd_HH = "yyyy-MM-dd HH";
    public static final String format_yyyyMMddHHmm = "yyyyMMddHHmm";
    public static final String format_yyyyMMdd = "yyyyMMdd";
    public static final String format_yyyy = "yyyy";
    public static final String format_yyyyMM = "yyyyMM";
    public static final String format_yyyy_MM_dd = "yyyy-MM-dd";
    public static final String format_MM_dd = "MM-dd";
    public static final String format_yyyyMMddHHmmss = "yyyyMMddHHmmss";
    public static final String format_yyyyCNMMCNddCN = "yyyy年MM月dd日";
    public static final String format_yyyyMMdd_bias = "yyyy/MM/dd";
    public static final String format_yyyyMMddhhmmss_bias = "yyyy/MM/dd HH:mm:ss";
    public static final String format_yyyyMMdd_bias_mmdd = "MM/dd";
    public static final String format_HHMM = "HH:mm";
    public static final String format_HHMMSS = "HH:mm:ss";
    public static final String[] weekStr = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"};

    public static final String format_twoPoint = "0.00";

    //========================================================人民币转大写===================================================
    private static final String[] CN_UPPER_NUMBER = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private static final String[] RADICES = {"", "拾", "佰", "仟"};
    private static final String[] BIG_RADICES = {"", "万", "亿", "兆"};


    /**
     * 整数除法保留两位小数
     * create by stan.ruan on 2017-12-25
     */
    public static String getTxFloat(String a) {
        int num = Integer.parseInt(a);
        DecimalFormat df = new DecimalFormat(format_twoPoint);
        return df.format((double)num / (double)100);
    }

    /**
     * 人名币转大写
     * create by stan.ruan on 2018-01-04
     */
    public static String getRMB(String moneyStr) {
        long money = Long.valueOf(moneyStr).longValue();
        StringBuilder result = new StringBuilder("");
        if (money == 0) {
            return "零元整";
        }
        if(money < 0){
            money = Math.abs(money);
        }
        long integral = money / 100;//整数部分
        int integralLen = (integral + "").length();
        int decimal = (int) (money % 100);//小数部分
        if (integral > 0) {
            int zeroCount = 0;
            for (int i = 0; i < integralLen; i++) {
                int unitLen = integralLen - i - 1;
                int d = Integer.parseInt((integral + "").substring(i, i + 1));//当前数字的值
                int quotient = unitLen / 4;//大单位的下标{"", "万", "亿"}
                int modulus = unitLen % 4;//获取单位的下标（整数部分都是以4个数字一个大单位，比如：个、十、百、千、个万、十万、百万、千万、个亿、十亿、百亿、千亿）
                if (d == 0) {
                    zeroCount++;
                } else {
                    if (zeroCount > 0) {
                        result.append(CN_UPPER_NUMBER[0]);
                    }
                    zeroCount = 0;
                    result.append(CN_UPPER_NUMBER[d]).append(RADICES[modulus]);
                }
                if (modulus == 0 && zeroCount < 4) {
                    result.append(BIG_RADICES[quotient]);
                }
            }
            result.append("元");
        }
        if (decimal > 0) {
            int j = decimal / 10;
            if (j > 0) {
                result.append(CN_UPPER_NUMBER[j]).append("角");
            }
            j = decimal % 10;
            if (j > 0) {
                result.append(CN_UPPER_NUMBER[j]).append("分");
            }
        } else {
            result.append("整");
        }
        return result.toString();
    }
    /**
     * 把string类小数转化为整数
     */
    public static String float2Int(String num){
        String str = String.valueOf(Double.parseDouble(num)*100);
        int i = str.indexOf(".");
        return str.substring(0,i);
    }
    /**
     * 把string类小数转化为整数
     */
    public static String float2Int1(String num){
        String str = num.trim();
        int i = str.length();
        int j = str.indexOf(".");
        String data = null;
        if((i-j) == 3){
             data = str.replace(".","");
        }else {
            str=str+"0";
            data = str.replace(".","");
        }
        return data;
    }
    /**
     * 正则表达式判断字符串是否是负整数,并且红冲金额要小于目前剩余的最大金额
     * create by stan.ruan on 2018-01-10
     * @param strMoney//红冲金额
     * @param bigMoney //剩余可红冲金额
     */
    public static boolean StrIsNumber(String strMoney, String bigMoney) {
        if (strMoney.matches("-0|(-[1-9]+(\\d)?)")) {
            int intMoney = Integer.parseInt(strMoney.substring(1, strMoney.length()));
            int bigIntmMoney = Integer.parseInt(bigMoney);
            System.out.println(intMoney);
            System.out.println(bigIntmMoney);
            if (intMoney <= bigIntmMoney) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    /*
       * 将时间转换为时间戳
       */
    public static String dateToStamp(String s) throws ParseException{
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /**
     * 将yyyymmddhhmmss转换成yyyy年mm月dd日
     * create by stan.ruan on 2018-01-04
     */
    public static String StrDateToStr(String strDate) {
        StringBuilder result = new StringBuilder("");
        result.append(strDate.substring(0, 4));
        result.append("年");
        result.append(strDate.substring(4, 6));
        result.append("月");
        result.append(strDate.substring(6, 8));
        result.append("日");
        return result.toString();
    }

    /**
     * 获取当前时间戳
     */
    public static String getReportFileStrDate() {
        return String.valueOf(System.currentTimeMillis());
    }

    /**
     * 获取当前时间的前一天的开始时间
     */
    public static Date getPreDate() {
        Date dNow = new Date();   //当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(dNow);//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
        dBefore = calendar.getTime();   //得到前一天的时间
        return dBefore;
    }
    //时间戳转化为日期
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    //时间戳转化为日期
    public static String stampToDate1(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    /**
     * 获取当前日期的前1天(yyyy-MM-dd)
     */
    public static String getPreOneDayYmd() {
        SimpleDateFormat format = new SimpleDateFormat(format_yyyy_MM_dd);
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime( new Date());//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
        return format.format(calendar.getTime()); //得到前一天的时间
    }
    /**
     * 获取当前日期的前1小时
     */
    public static String getPreOneDayYmdhms() {
        SimpleDateFormat format = new SimpleDateFormat(format_yyyy_MM_dd_HHmmssSSS);
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime( new Date());//把当前时间赋给日历
        calendar.add(Calendar.HOUR, -1);  //设置为前一小时
        return format.format(calendar.getTime()); //得到前一小时的时间
    }
    /**
     * 当前日期(yyyy-MM-dd)
     *
     * @return date
     */
    public static String getToDayYmd() {

        SimpleDateFormat format = new SimpleDateFormat(format_yyyy_MM_dd);
        return format.format(new Date());

    }
    /**
     * 获取当前时间（yyyy-MM-dd HH:mm:ss）
     *
     */
    public static String getCurrentStrDate() {
        SimpleDateFormat sdf = new SimpleDateFormat(format_yyyy_MM_dd_HHmmssSSS);
        return sdf.format(new Date());
    }

//    /**
//     * 获取当前时间（毫秒）（yyyy-MM-dd HH:mm:ss.SSS）
//     *
//     */
//    public static String  getCurrentDate() {
////        Long current = System.currentTimeMillis();
//        SimpleDateFormat sdf = new SimpleDateFormat(formatDefaultTimestamp);
//        return sdf.format(new Date());
//    }

    /**
     * 日期转换成字符串
     *
     * @param date
     * @return str
     * "yyyy-MM-dd HH:mm:ss"
     */
    public static String DateToStr(Date date, String strFormat) {
        if (StringUtils.isEmpty(strFormat)) {
            strFormat = formatDefaultTimestamp;
        }
        SimpleDateFormat format = new SimpleDateFormat(strFormat);
        String str = "";
        if (date != null) {
            str = format.format(date);
        }
        return str;
    }

    /**
     * 日期转换成字符串
     *
     * @param date
     * @return str
     * "yyyy年MM月dd日"
     */
    public static String DateToStrTwo(Date date) {

        SimpleDateFormat format = new SimpleDateFormat(format_yyyyCNMMCNddCN);
        String str = "";
        if (date != null) {
            str = format.format(date);
        }
        return str;
    }


    /**
     * 字符串转换成日期
     *
     * @param str
     * @return date
     */
    public static Date StrToDate(String str, String strFormat) {

        SimpleDateFormat format = new SimpleDateFormat(strFormat);
        Date date = null;
        try {
            if(str == null || str == ""){
                return null;
            }

            return format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 字符串转换成日期(yyy年MM月dd日)
     *
     * @param str
     * @return date
     */
    public static String StrToDateYmd(String str) {

        SimpleDateFormat format = new SimpleDateFormat(format_yyyy_MM_dd);
        Date date = null;
        if (StringUtils.isEmpty(str)) {
            return format.format(new Date());
        }
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return format.format(date);
    }

    /**
     * 字符串转换成指定日期字符串日期(yyy年MM月dd日)
     *
     * @param str
     * @return String
     */
    public static String YmdStrToMMyy(String str) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = format.parse(str);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat format1 = new SimpleDateFormat("MMyy");
        return format1.format(date);
    }
    /**
     * 将字符串中的特殊符号去掉例如@#￥%=+-....
     *
     * @param str
     * @return String
     */
    public static String NotString(String str) {

        return str.replaceAll("\\p{Punct}","");
    }
    /**
     * 验证时间距离当前时间时长是否超过指定时长
     * 主要用于接口header的时间戳验证
     *
     * @param strDate 检查日期
     * @param llength 规定时长
     *                return Boolean true:通过，fales：不通过
     */
    public static Boolean checkDateLong(String strDate, long llength) {
        if (StringUtils.isEmpty(strDate)) {
            return false;
        }

        if (System.currentTimeMillis() - StrToDate(strDate,formatDefaultTimestamp).getTime() - llength >= 0L) {
                return false;
        } else {
            return true;
        }
    }

    /**
     * 计算两个日期直接相差毫秒
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     *                  return Boolean true:通过，fales：不通过
     */
    public static String getConsumeTime(String startDate, String endDate) {
        return String.valueOf(StrToDate(endDate,formatDefaultTimestamp).getTime() - StrToDate(startDate,formatDefaultTimestamp).getTime());
    }

    /**
     * 计算两个日期直接相差毫秒是否满足
     *
     * @param time
     * @param pattern return Boolean true:通过，fales：不通过
     */
    public static boolean isThisTime(long time, String pattern) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String param = sdf.format(date);//参数时间
        String now = sdf.format(new Date());//当前时间
        if (param.equals(now)) {
            return true;
        }
        return false;
    }

    /**
     * 距离当前时间88天之内的日期
     *
     * @param time type:1--88天之内的
     * @return
     */
    public static boolean getDayDiffFromToday(String time) {
        //将字符串转为日期：yyyyMMddHHmmss
        SimpleDateFormat sdf = new SimpleDateFormat(format_yyyyMMddHHmmss);
        Date param = null;//参数时间
        try {
            param = sdf.parse(time);
            long s1 = param.getTime();//将时间转为毫秒
            long s2 = System.currentTimeMillis();//得到当前的毫秒
            int day = Math.toIntExact((s2 - s1) / 1000 / 60 / 60 / 24);
            if (day >= 0 && day <= 88) {
                return true;
            }
        } catch (ParseException e) {
            return false;
        }
        return false;
    }

    /**
     * 距离当前时间88天之内的日期
     *
     * @param time type:1--88天之内的
     * @return
     */
    public static boolean getDayDiffFromToday1(String time) {
        //将字符串转为日期：yyyyMMddHHmmss
        SimpleDateFormat sdf = new SimpleDateFormat(format_yyyyMMddHHmmss);
        Date param = null;//参数时间
        try {
           param = sdf.parse(time);
            long s1 = Long.valueOf(time);//将时间转为毫秒
            long s2 = System.currentTimeMillis();//得到当前的毫秒
            int day = Math.toIntExact((s2 - s1) / 1000 / 60 / 60 / 24);
            if (day >= 1 && day <= 88) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    /**
     * 获取前一天的时间
     * @return
     */
    public static String PreDate() {
        Date dNow = new Date();   //当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(dNow);//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
        dBefore = calendar.getTime();   //得到前一天的时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
        String defaultStartDate = sdf.format(dBefore);    //格式化前一天
        String defaultEndDate = defaultStartDate.substring(0,10)+" 23:59:59";
        return defaultEndDate;
    }

    /**
     * 前六后四 隐藏银行卡号
     *
     * @param cardNo
     * @return java.lang.String
     *
     */
    public static String hideCardNo(String cardNo) {
        if (StringUtils.isBlank(cardNo)) {
            return cardNo;
        }
        if (cardNo.length() > 10) {
            //前六后四
            StringBuilder stringBuilder = new StringBuilder();
            return stringBuilder.append("****  ****  ****  ")
                    .append(cardNo.substring(cardNo.length() - 4)).toString();
        } else {
            return cardNo;
        }
    }

   public static void main(String[] args) {
       // String data = "4805.9";

       // System.out.println(MyDateUtil.getTxFloat("1965310401"));
      //  System.out.println(data.replace(".",""));

       //System.out.println(MyDateUtil.getDayDiffFromToday1("1540643089000"));

       System.out.println(MyDateUtil.getTxFloat("201711"));
    }
}
